var form = layui.form,
    id=getQueryVariable("id"),
    type=getQueryVariable("type"),
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    layer = layui.layer
;



laydate.render({
    elem: '#rdate'
    ,type: 'datetime'
});
//获取供应商
var gys=getgys();

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                //接收人不包含自己
                if (it.code!=user.code){
                    item["list"].push(it)
                }
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: '500px',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
var receiverCodeList=[];
layer.ready(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if (treeList && treeList.list) {
        let userTree = getAllJson(treeList.list);
        receiverCodeList= getxmselect("#receiverCode", "receiverCode", userTree);
    } else {
        receiverCodeList= getxmselect("#receiverCode", "receiverCode", [{name: user.name, value: user.code}])
    }

    var gysselect=$("select[name='customerCode']");//供应商
    gysselect.append(getoption(gys));

})



form.render();
//表单初始值，修改时调用
if(id!=""){
    var obj=queryByid();
    form.val("customercontact-form",{
        "contact":obj.contact,
        "remindTime":obj.remindTime,
        "content":obj.content,
        "customerCode":obj.customerCode,
        "customerName":obj.customerName
    })

}

//监听客户名称下拉框
form.on('select(customerCode)', function (data) {
    if(data.value === ""){
        return;
    }
    $("#customerName").val(getInStorePerson(data.value));
})

function getInStorePerson(code){
    for(let i in gys){
        if(gys[i].code == code){
            return gys[i].name;
        }
    }
    return "";
}
//监听提交
form.on('submit(form-element)', function(data){
    //追加当前登录人,接收人也有自己
    if(data.field.receiverCode=="" || data.field.receiverCode==null){
        data.field.receiverCode=user.code;
    }else{
        data.field.receiverCode=data.field.receiverCode+","+user.code
    }
    if(saveMessage(data.field)){
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/BasicData/message.jsp","消息");
            parent.intab("views/jsp/BasicData/message.jsp","消息");
            parent.detab("views/jsp/BasicData/tpl/newupcustomercontact.jsp?id="+id+"&type="+type,"修改客户联系");
            parent.detab("views/jsp/BasicData/tpl/newupcustomercontact.jsp?type="+type,"新增客户联系");
        },1000)
    }else{
        layer.msg("保存失败", {icon: 6});
    }

    return false;
});

function queryByid() {
    var obj=[];
    $.ajax({
        type : 'get',
        data:{"id":id},
        url:'message/queryByid',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
                let receiverCodeArray=da.data.receiverCode.split(",");
                receiverCodeList.setValue(receiverCodeArray);
            }
        }
    });
return obj;
}
function saveMessage(data) {
    if(id !="") data.id=id;
    data.messageType=type;

    var tf=false;

    $.ajax({
        type : 'post',
        //  url : 'resource/getTree',
        data:JSON.stringify(data),
        url:'message/saveMessage',
        dataType:"json",
        contentType: 'application/json',

        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}
//获取所有供应商
function  getgys() {
    var gys=[];
    $.ajax({
        type : 'get',
        url:'customer2/getAllGys',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                for(var i=0;i<da.data.length;i++){
                    var obj={};
                    obj.code=da.data[i].code;
                    obj.name=da.data[i].name;
                    gys.push(obj);
                }

            }
        }
    });
    return gys;
}
function  getoption(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}